// api.ts
// 统一 API 封装（支持 .env 的 VITE_API_BASE；否则默认走 /api，配合 vite 代理）
import * as http from "http";

const ENV_BASE = (import.meta as any).env?.VITE_API_BASE
const BASE_URL: string = ENV_BASE && ENV_BASE.trim()
    ? ENV_BASE.trim().replace(/\/+$/,'')
    : '/api'

const IS_H5 = typeof window !== 'undefined'

const __BASE__ = (typeof BASE_URL !== 'undefined' && BASE_URL) ? (BASE_URL as string).replace(/\/+$/, '') : ''

export async function apiFetch(url: string, options: RequestInit = {}) {
    const sid = localStorage.getItem('sid')
    const headers: Record<string, string> = {
        'Content-Type': 'application/json',
        ...(options.headers || {}),
    }

    if (sid) {
        headers['X-Auth-Token'] = sid
    }

    const resp = await fetch(url, {
        ...options,
        headers,
    })

    if (!resp.ok) {
        throw new Error(`HTTP error! status: ${resp.status}`)
    }

    return resp.json()
}

function toQuery(params: Record<string, any>) {
    const sp = new URLSearchParams()
    Object.entries(params).forEach(([k, v]) => {
        if (v === undefined || v === null) return
        if (typeof v === 'string' && v.trim() === '') return
        sp.set(k, String(v))
    })
    const qs = sp.toString()
    return qs ? `?${qs}` : ''
}


export default http;

function request<T = any>(opts: UniApp.RequestOptions & { showError?: boolean }): Promise<T> {
    const token = uni.getStorageSync('TOKEN') || ''
    const isAbs = opts.url?.startsWith('http')
    const url = isAbs ? (opts.url as string) : `${BASE_URL}${opts.url}`

    const sid = uni.getStorageSync('SID') || ''
    const header: Record<string, string> = {
        'Content-Type': 'application/json',
        ...(opts.header || {}),
        ...(sid ? { 'X-Auth-Token': sid } : {})   // ★ 关键
    }

    return new Promise((resolve, reject) => {
        uni.request({
            url,
            method: (opts.method as any) || 'GET',
            header: { 'Content-Type': 'application/json', Authorization: token, ...(opts.header || {}) },
            data: opts.data || {},
            success: (res) => {
                const code = (res.data as any)?.code
                const data = (res.data as any)?.data ?? res.data
                if (code === undefined || code === 0) resolve(data as T)
                else {
                    if (opts.showError !== false) uni.showToast({ title: (res.data as any)?.msg || '请求失败', icon: 'none' })
                    reject(res.data)
                }
            },
            fail: (err) => { if (opts.showError !== false) uni.showToast({ title: '网络错误', icon: 'none' }); reject(err) }
        })
    })
}


export interface RmcRecordDTO {  // 混凝土记录表
    id?: number
    projectId: number
    weather?: string
    temperature?: string
    pageNo?: number
    supplyUnit?: string
    designStrength?: string
    mixPlant?: string
    contactPhone?: string
    pouringDateStart?: string  // ISO 字符串
    pouringDateEnd?: string    // ISO 字符串
    slump?: string
    continuousTime?: string
    initialSetting?: string
    cubeStrength?: string
    truckNos?: string[]
    checklist?: Array<{ no: number | string; title: string; result: string }>
    samplingTimes?: number
    samplingValues?: number[]
    cubeGroupsCurr?: number
    cubeGroupsMid?: number
    cubeGroupsSpl?: number
    rebarValue?: string
    inspectorOpinion?: string
    recorder?: string
    isTrue?: boolean
    // 可按需补充
}


export const api = {
    // 用户
    me:            () => request<{username:string}>({ url:'/api/user/me' }),
    // login:         (data:{username:string;password:string}) => request({ url:'/api/user/login', method:'POST', data }),
    // login: (p:{username:string; password:string}) =>
    //     request<{ data:any; headers:Record<string,string> }>({
    //         url:'/api/auth/login',
    //         method:'POST',
    //         data:p,
    //         returnHeaders:true,   // 允许拿到响应头
    //     }),
    // login: (p: { username: string; password: string }) =>
    //     request<any>({ url: '/api/user/login', method: 'POST', data: p }),
    // async login(username: string, password: string) {
    //     const data = await apiFetch('/api/user/login', {
    //         method: 'POST',
    //         body: JSON.stringify({ username, password }),
    //     })
    //     // 登录成功后保存 sid
    //     localStorage.setItem('sid', data.sessionId)
    //     return data
    // },
    async login(payload: { username: string; password: string }) {
        return apiFetch('/api/user/login', {
            method: 'POST',
            body: JSON.stringify(payload), // ✅ 直接序列化对象
        });
    },
    // 首页指标
    homeMetrics:   () => request<{todo:number;doneToday:number;abnormal:number}>({ url:'/api/home/metrics' }),
    // 任务
    // fetchTasks: (p: { state:'todo'|'done'; page?:number; size?:number; keyword?:string; projectId?:number }) =>
    //     request<{ page:number; size:number; total:number; items:any[] }>({ url:'/api/tasks', data:p }),  // 任务列表
    // fetchTasks: (p: { state:'todo'|'done'; page?:number; size?:number; keyword?:string; projectId?:number }) =>
    //     apiFetch<{ page:number; size:number; total:number; items:any[] }>('/api/tasks', { method:'GET', data:p }),
    fetchTasks: (p: {
        state: 'todo' | 'done'
        page?: number
        size?: number
        keyword?: string
        projectId?: number
    }) => {
        const qs = toQuery(p)
        return apiFetch(`/api/tasks${qs}`, { method: 'GET' })
    },
    getTaskDetail: (id: string | number) => request<any>({ url: `/api/tasks/${id}` }),  // 任务详情
    submitManual:  (body:any) => request({ url:'/api/tasks/submit/manual', method:'POST', data:body }),
    submitDevice:  (body:any) => request({ url:'/api/tasks/submit/device', method:'POST', data:body }),

    // ===================== NEW 开始：手动填报接口（与后端对齐） =====================
    /** 获取“手动填报”动态表单 Schema */
    // getManualForm: (id: number | string) =>
    //     request<any>({ url: `/api/tasks/${id}/manual-form`, method: 'GET' }),
    // session获取用户id
    getManualForm: (id: number | string) =>
        apiFetch(`/api/tasks/${id}/manual-form`, { method: 'GET' }),

    // api.ts
    // getManualForm: (taskId: number, userId: number) =>
    //     request<any>({ url: `/api/tasks/${taskId}/manual-form`, method: 'GET' }),

    // getManualForm: (taskId: number, userId: number) =>
    //     request<any>({
    //         url: `/api/tasks/${taskId}/manual-form?userId=${encodeURIComponent(userId)}`,
    //         method: 'GET',
    //     }),

    // 建议把 userId 设为可选，并只在有值时拼到 URL
    // getManualForm: (taskId: number, userId?: number) => {
    //     const q = userId != null ? `?userId=${userId}` : '';
    //     return request<any>({
    //         url: `/api/tasks/${taskId}/manual-form${q}`,
    //         method: 'GET',
    //     });
    // },



    /** 动态获取记录模板；未配置时后端可返回 204 或空串 */
    // getRecordTemplate: (taskType: string, itemKey: string) =>
    //     request<string>({
    //         url: '/api/record-template',
    //         method: 'GET',
    //         // 走 query 参数，保持你的 request 习惯
    //         params: { taskType, itemKey },
    //         // 如果你 request 默认把 text 当 JSON 解析，这里要明确告诉它按 text 处理
    //         responseType: 'text' as any,   // 视你封装而定；若不支持可去掉
    //         // 如果后端是 204，这里放行，调用方自己做回退
    //         validateStatus: (status: number) => [200, 204].includes(status),
    //     }),
    // getRecordTemplate: (taskType: string, itemKey: string) =>
    //     request<string>({
    //         url:
    //             `/api/record-template` +
    //             `?taskType=${encodeURIComponent(taskType)}` +
    //             `&itemKey=${encodeURIComponent(itemKey)}`,
    //         method: 'GET',
    //     }),
    // 调用套话，只传item_en版
    getRecordTemplateByItem: (itemKey: string) =>
        request<string>({
            url: `/api/record-template?itemKey=${encodeURIComponent(itemKey)}`,
            method: 'GET',
        }),

    /**
     * 保存“手动填报”数据
     * @param id       任务ID
     * @param taskType 任务类型（如 rebar_material）
     * @param body     { items: [...] }
     *
     * 说明：当前 request 不带 params 参数，这里直接把 taskType 拼到 query 上。
     */
    saveManualForm: (id: number | string, taskType: string, body: any) =>
        request<any>({ url: `/api/tasks/${id}/manual-form?taskType=${encodeURIComponent(taskType)}`, method:'POST', data: body }),
    // ===================== NEW 结束 =====================

    // 上传示例：根据你后端实际改造；先返回空数组也能跑通
    uploadBatch:   async (_files:any[]) => { return [] as string[] },

    // （可选）NEW：单文件上传，供“上传照片 / PDF”使用；若页面未用可忽略
    uploadFile: (filePath: string, kind: 'photo' | 'pdf' = 'photo') =>
        new Promise<{url:string}>((resolve, reject) => {
            uni.uploadFile({
                url: `${BASE_URL}/api/files/upload`,  // 如果你的后端是 /api/files/upload
                name: 'file',
                filePath,
                formData: { kind },
                success: (res) => {
                    try { resolve(JSON.parse(res.data)) } catch { resolve({ url: res.data as any }) }
                },
                fail: reject
            })
        }),

    // === 占位：从智能设备系统导入数据（后端未实现也可先占位） ===
    importDeviceData: (taskId: number | string) =>
        request<any>({ url: `/api/device/import`, method: 'POST', data: { taskId } }),

    // === 占位：向上游系统发送数据（后端未实现也可先占位） ===
    pushUpstream: (taskId: number | string, taskType: string, body: any) =>
        request<any>({ url: `/api/tasks/${taskId}/upstream`, method: 'POST', data: { taskType, ...body } }),

    // 项目
    fetchProjects: (p:{kw?:string}) => request<any[]>({ url:'/api/projects', data:p }),
    getProject:    (id:string) => request<any>({ url:`/api/projects/${id}` }),
    // getMyProjects: () => request<any[]>({ url: '/api/projects/my' }),
    // getMyProjectsByUserCode: (userCode: string) => request<any[]>({ url: '/api/projects/my', method: 'GET', data: { userCode } }),
    // getMyProjects: () =>
    //     request<any[]>({ url: '/api/projects/my', method: 'GET' }),
    async getMyProjects() {
        return apiFetch('/api/projects/my', { method: 'GET' })
    },
    // 报表
    genReport:     (p:{type:'rebar'|'concrete', id?:string}) => request<string>({ url:'/api/reports/gen', data:p }),

    // 其他
    syncPeople:    () => request({ url:'/api/people/sync', method:'POST', data:{} }),
}

export const rmc = {
    /** 新增/更新记录，返回 { id } */
    save: (data: RmcRecordDTO) =>
        request<{ id: number; ok: boolean }>({
            url: `/api/rmc/save`,
            method: 'POST',
            data,
        }),

    /** 获取单条记录详情 */
    getById: (id: number) =>
        request<any>({
            url: `/api/rmc/${id}`,
            method: 'GET',
        }),

    /** 按项目查询列表（如后端支持分页可传 page/size） */
    listByProject: (projectId: number, page?: number, size?: number) =>
        request<any>({
            url:
                `/api/rmc/project/${projectId}` +
                (page && size ? `?page=${page}&size=${size}` : ''),
            method: 'GET',
        }),

    /** 导出 PDF（与截图样式一致） */
    // exportPdf: (id: number, projectName?: string) =>
    //     request<Blob>({
    //         url:
    //             `/api/rmc/${id}/export` +
    //             (projectName ? `?projectName=${encodeURIComponent(projectName)}` : ''),
    //         method: 'GET',
    //         responseType: 'blob',
    //     }),
    /**
     * 导出 PDF：
     * - H5：使用 fetch 携带 X-Auth-Token，返回 Blob（自行触发下载）
     * - 其他端：使用现有 request，responseType=arraybuffer，返回 ArrayBuffer
     */

    exportPdf: async (id: number, projectName?: string): Promise<Blob | ArrayBuffer> => {
        const path = `/api/rmc/${id}/export${toQuery({ projectName })}`
        if (IS_H5) {
            const sid = localStorage.getItem('sid') || localStorage.getItem('SID') || ''
            const res = await fetch(__BASE__ + path, {
                method: 'GET',
                headers: sid ? { 'X-Auth-Token': sid } as any : undefined,
            })
            if (!res.ok) throw new Error(`HTTP ${res.status}`)
            return res.blob()
        }
        // 非 H5
        return request<ArrayBuffer>({
            url: path,
            method: 'GET',
            // @ts-ignore uni.request 支持 responseType
            responseType: 'arraybuffer',
        })
    },


}

/** （可选）H5 下载帮助：把 Blob 触发为文件下载 */
export function downloadBlob(blob: Blob, filename: string) {
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = filename
    a.click()
    URL.revokeObjectURL(url)
}

export interface RebarRecordDTO {
    id?: number
    projectId: number
    constructionUnit?: string
    serialNo?: string
    rebarSpec?: string
    jointCount?: number
    performanceLevel?: string
    operatorName?: string
    cutSpecResult?: string
    mechSpecResult?: string
    installDateS?: string   // ISO 字符串
    installDateE?: string
    position?: string
    standard?: string
    appearanceCheck?: string
    pressValues?: number[]
    checklist?: Array<{ no: number | string; title: string; result: string }>
    constructionEvaluation?: string
    supervisorConclusion?: string
    remark?: string
    techLeaderName?: string
    techLeaderDate?: string
    supervisorEngineerName?: string
    supervisorEngineerDate?: string
    recorder?: string
    projectDeptSealDate?: string
}

export const rebar = {
    save: (data: RebarRecordDTO) =>
        request<{ id: number; ok: boolean }>({ url: `/api/rebar/save`, method: 'POST', data }),
    getById: (id: number) =>
        request<any>({ url: `/api/rebar/${id}`, method: 'GET' }),
    listByProject: (projectId: number) =>
        request<any>({ url: `/api/rebar/project/${projectId}`, method: 'GET' }),
    exportPdf: (id: number, projectName?: string) =>
        // 统一走 request（二进制）
        request<ArrayBuffer>({
            url: `/api/rebar/${id}/export${toQuery({ projectName })}`,
            method: 'GET',
            // @ts-ignore
            responseType: 'arraybuffer',
        }),
}